
#include "base_malloclib.h"


/* 增加fake层 */

/* 引入mmapheap */
#include <metalc/mlos/mmapheap.h>
/* 可以修改大小的*/
DEF_MMAPHEAP_MLAYER(mmapheap_normal, BIT(16), SIZE_1G, SIZE_64G, 0, 0)

/* DECOMMIT太小了会不会造成性能下降？ */
/* 改成128K应该会缓解 */
#ifndef WSLINUX
	#define SEGLF_DECOMMIT_MINSIZE	(SIZE_256K)	/* 超过该大小应该释放给操作系统内核 */
#endif

#include <metalc/mlayer/segfit_lf.h>

SAI void mark_used(void *ptr, size_t size){
	os_commit(ptr, size);
}
SAI void mark_unused(void *ptr, size_t size){
	/* MADV_FREE和MADV_DONTNEED的内核路径差不多，后者能减少RSS */

	os_decommit_lazy(ptr, size, 1); // lazy decommit
	// os_decommit_dontneed(ptr, size); // dontneed
}
DEF_SEGLF_2B_MLAYER(seglf_bin_ext, 16, HDEF_PTR_BITS, SIZE_4K, mark_used, mark_unused, mlcc_palloc, page_alloc)


/* 定义wfspan */
#include <metalc/mlayer/wfspan_nomblock.h>
DEF_CLS_SUPER_CLS2SZTBL(super, 4, 15, MANTISSA_BITS_DEFAULT, LOW_BITS_DEFAULT)

/* 使用转换表加速 */
#define WFSPAN_SLABSIZE		65536
#define WFSLAB_CLS_UNITNR(cls)	((WFSPAN_SLABSIZE - sizeof(mslab_t))/__cls2sz_super(cls, MANTISSA_BITS_DEFAULT, LOW_BITS_DEFAULT))
#define WFSLAB_SLABLIMIT_K	64	/* 线程拥有的slab数量限制 */
#define WFSLAB_FRAC_P		1	/* 查询线程个数为(当前总线程数 >> frac_p)，0为遍历全部线程 */
#define WFSLAB_HELPQUOTA_H	1	/* 帮助限额，除了wfqueue protocol帮助协议外，每次帮助推进1次即可 */

SIN hword_t unitsz2maxnr(szcls_t cls){
	/* 提前算好的, 39个map映射表 */
	/* 公式是(MSLAB_SIZE - sizeof(mslab_t))/unit_size */
	static const uint16_t maptable[] = {
		MAPC(WFSLAB_CLS_UNITNR, RANGE8(39))};
	// static const uint16_t maptable[] = {4088, 2044, 1362, 1022, 817, 681, 584, 511, 408, 340, 292, 255, 204, 170, 146, 127, 102, 85, 73, 63, 51, 42, 36, 31, 25, 21, 18, 15, 12, 10, 9, 7, 6, 5, 4, 3, 3, 2, 2};
	ASSERT(cls < _clsnr_super);
	return (hword_t)maptable[cls];
}
/* 问题出在窃取这边 */
/* 如果满了则尝试无锁出队? */
/* K大小 */

DEF_WFSLAB_MLAYER(wfspan, 4, 15, WFSPAN_SLABSIZE, WFSLAB_SLABLIMIT_K, WFSLAB_FRAC_P, WFSLAB_HELPQUOTA_H, super, unitsz2maxnr, mlcc_palloc)



#include <metalc/mladt/fake.h>
DEF_FAKE_MLAYER(fake1)
DEF_FAKE_MLAYER(fake2)
DEF_FAKE_MLAYER(fake3)
/* 组合 */
COMPOSE_MLAYER(malloc_wfslab, mallocapi, fake1, wfspan, fake2, seglf_bin_ext, fake3, mmapheap_normal)

/* 定义tls */
DEF_MTLS_PTHREAD(GET_MLAYER_OBJNR(malloc_wfslab), 4096, mlcc_palloc, mp_coreid)

/* mlcc和mtls一定要放在第一位初始化 */
DEF_SYSINIT(malloc_perm_pool, malloc_wfslab, mtls)
DEF_CFLOWINIT(mtls, malloc_wfslab)
DEF_CFLOWFIN(mtls)
DEF_SYSFIN(__omega)